package com.project.collectAPI.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.project.collectAPI.comm.jwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 实现header token拦截
 */

public class JWTinterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("请求的Uri资源*************************:"+request.getRequestURI());
        /*String superAdmin=request.getHeader("superAdmin");
        String superLogin=request.getHeader("superLogin");
        if(!StringUtils.isEmpty(superAdmin) && !StringUtils.isEmpty(superLogin)){
            if(superAdmin.equals("888") && superLogin.equals("888")) {
                return true;
            }
        }*/
        Map<String,Object> map=new HashMap<>();
        try {
            String token=request.getHeader("token");
            if(StringUtils.isEmpty(token)){
                map.put("msg","token不存在");
                //将map转换为json
                String json=new ObjectMapper().writeValueAsString(map);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println(json);
                return false;
            }
            //获取请求头中的令牌
            jwtUtils.verify(token);
            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg","无效签名!");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token过期!");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","token无效!!");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","token不存在");
        }
        map.put("state",false); //设置状态
        //将map转换为json
        String json=new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
